package com.example.demo;


import javax.jms.ConnectionFactory;

import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.messaginghub.pooled.jms.JmsPoolConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.core.JmsTemplate;

@Configuration
@EnableConfigurationProperties(ArtemisProperties.class)
public class ArtemisConfig {
	protected static final Logger log = LoggerFactory.getLogger(ArtemisConfig.class);
	protected boolean t = true;
	protected boolean f = false;

	@Autowired
	private ArtemisProperties artemisProperties;
	
	@Bean(name="jmsListenerContainerFactory")
    public DefaultJmsListenerContainerFactory jmsQueueListenerContainerFactory(JmsPoolConnectionFactory cf) {
        DefaultJmsListenerContainerFactory factory =
                new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(cf);
        //重连间隔时间
        factory.setRecoveryInterval(1000L);
        factory.setAutoStartup(true);
        factory.setPubSubDomain(false);
        
        return factory;
    }
	@Bean
	public ActiveMQConnectionFactory createArtemisFactory() {
		ActiveMQConnectionFactory cf=new ActiveMQConnectionFactory(artemisProperties.getUri(),artemisProperties.getUsername(),artemisProperties.getPassword());
		return cf;
	}
	
	@Bean("consumerSize")
	public int getConsumerSize(ActiveMQConnectionFactory cf) {
		return cf.getThreadPoolMaxSize();
	}
	@Bean(name="jmsConnectionFactory")
	public JmsPoolConnectionFactory createFactory(ActiveMQConnectionFactory cf) {
		cf.getServerLocator().setUseTopologyForLoadBalancing(false);
		cf.setFailoverOnInitialConnection(true);
		cf.setConfirmationWindowSize(-1);
		JmsPoolConnectionFactory pcf = new JmsPoolConnectionFactory();
		pcf.setConnectionFactory(cf);
		pcf.setMaxConnections(16);
		//pcf.setConnectionCheckInterval(60000);
		
		return pcf;
	}

	
	@Bean(name = "jmsTemplate")
	public JmsTemplate jmsTemplate(ConnectionFactory cf){
		JmsTemplate jmsTemplate = new JmsTemplate();
		try {
			jmsTemplate = new JmsTemplate(cf);
		}
		catch(Exception e) {
			log.error("error",e);
		} 
		return jmsTemplate;
	}


}
